package com.campus.lostandfound.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.lostandfound.entity.Announcement;
import com.campus.lostandfound.mapper.AnnouncementMapper;
import com.campus.lostandfound.service.AnnouncementService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 公告Service实现类
 */
@Service
public class AnnouncementServiceImpl extends ServiceImpl<AnnouncementMapper, Announcement> implements AnnouncementService {
    
    @Override
    @CacheEvict(value = "announcement", allEntries = true)
    public boolean publishAnnouncement(Announcement announcement) {
        announcement.setStatus(1); // 已发布
        announcement.setPublishTime(LocalDateTime.now());
        
        // 设置过期时间（默认30天）
        if (announcement.getExpireTime() == null) {
            announcement.setExpireTime(LocalDateTime.now().plusDays(30));
        }
        
        System.out.println("【缓存】清除公告列表缓存");
        return save(announcement);
    }
    
    @Override
    @Cacheable(value = "announcement", key = "#current + '_' + #size")
    public IPage<Announcement> getAnnouncementList(Integer current, Integer size) {
        Page<Announcement> page = new Page<>(current, size);
        LambdaQueryWrapper<Announcement> wrapper = new LambdaQueryWrapper<>();
        
        // 只查询已发布且未过期的公告
        wrapper.eq(Announcement::getStatus, 1);
        wrapper.gt(Announcement::getExpireTime, LocalDateTime.now());
        
        // 紧急通知优先，然后按发布时间倒序
        wrapper.orderByDesc(Announcement::getType);
        wrapper.orderByDesc(Announcement::getPublishTime);
        
        System.out.println("【缓存】从数据库查询公告列表: page=" + current);
        return page(page, wrapper);
    }
}

